-- 追踪投射物

local MissionWeapon = TaleWorlds.MountAndBlade.MissionWeapon

local onlyPlayer = true
local track_distance = 15
local track_split = true
local behavior

return {
onBeforeMissionBehaviorInitialize = function (mission)
    behavior = SubModule:CreateMissionBehavior({
        onAgentShootMissile = function (shooterAgent, weaponIndex, position, velocity, orientation, hasRigidBody, forcedMissileIndex)
            if onlyPlayer and not shooterAgent.IsMainAgent then
                return
            end

            local weapon = shooterAgent.Equipment[weaponIndex]
            if weapon == MissionWeapon.Invalid or weapon.CurrentUsageItem == nil then
                return
            end

            local missileSpeed = weapon:GetModifiedMissileSpeedForCurrentUsage()

            behavior:SetTimeout(200, function (dt)
                local missiles = SubModule:GetMissiles()
                for i = missiles.Count - 1, 0, -1 do
                    local missile = missiles[i]
                    if missile.ShooterAgent ~= shooterAgent then
                        goto continue
                    end

                    local pos = missile.Entity.GlobalPosition
                    local agents = SubModule:CreateAgentList()
                    mission:GetNearbyEnemyAgents(pos.AsVec2, track_distance, shooterAgent.Team, agents)
                    local flag = false

                    for j = 0, agents.Count - 1, 1 do
                        -- if shooterAgent.IsMainAgent then
                        --     InformationManager.DisplayMessage(InformationMessage("触发追踪！", Colors.Yellow))
                        -- end
                        local agent = agents[j]
                        local boneFrame = agent.AgentVisuals:GetSkeleton():GetBoneEntitialFrameWithName("head") -- 追踪头部
                        local globalFrame = agent.AgentVisuals:GetGlobalFrame()
                        local posFrame = globalFrame:TransformToParent(boneFrame)
                        local dir = posFrame.origin - pos
                        dir:Normalize()
                        local identity = Mat3.Identity
                        identity.f = dir
                        identity:Orthonormalize()
                        mission:AddCustomMissile(shooterAgent, missile.Weapon, pos, identity.f, identity, missileSpeed, missileSpeed + 20 * MBRandom.RandomFloat, hasRigidBody, missile.MissionObjectToIgnore, -1)
                        flag = true
                        if not track_split then
                            break
                        end
                    end
                    if flag then
                        missile.Entity:Remove(80)
                        mission:RemoveMissileAsClient(missile.Index)
                    end
                    ::continue::
                end
            end)
        end
    })
    mission:AddMissionBehavior(behavior)
end
}